package com.yxjx.duoxue.course;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.yxjx.duoxue.R;
import com.yxjx.duoxue.customview.OutScrollView;
import com.yxjx.duoxue.customview.YxListView;
import com.yxjx.duoxue.datamodel.DMTeacher;
import com.yxjx.duoxue.datamodel.course.DMCourse;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

public class YxItemList extends ListView {

	private ArrayList<Object> mData;
	
	public YxItemList(Context context, AttributeSet attrs) {
		super(context, attrs);
		setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (mData.get(0) instanceof DMCourse) {
					DMCourse course = (DMCourse) mData.get(arg2);
					Intent intent = new Intent(getContext(),
							CourseIntroductionActivity.class);
					intent.putExtra(NwUtils.KEY_ID, "" + course.getCourseId());
					getContext().startActivity(intent);
				} else if (mData.get(0) instanceof DMTeacher) {
					DMTeacher teacher = (DMTeacher) mData.get(arg2);
					Intent intent = new Intent(getContext(), TeacherIntroductionActivity.class);
					intent.putExtra(NwUtils.KEY_ID, "" + teacher.getId());
					getContext().startActivity(intent);
				}
			}
		});
	}
	
	public class YxItemListAdapter extends BaseAdapter {
		
		public void setData(ArrayList<? extends Object> data) {
			mData = (ArrayList<Object>) data;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return mData == null ? 0 : mData.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret = null;
			
			// customize course/teacher data;
			if (mData != null && mData.get(arg0) instanceof DMCourse) {
				if (arg1 == null) {
					ret = LayoutInflater.from(getContext()).inflate(
							R.layout.item_list_course, null);
				} else {
					ret = arg1;
				}
				
				DMCourse course = (DMCourse) mData.get(arg0);
				UIHelper.setText(ret, R.id.course_name, course.getCourseName());
				UIHelper.setText(ret, R.id.category_and_requirement,
						Utils.getCategoryText(course));
				UIHelper.asyncLoadImage(
						(ImageView) ret.findViewById(R.id.course_icon),
						course.getHeadImageUrl(), R.drawable.default_icon);
			} else if (mData != null && mData.get(arg0) instanceof DMTeacher) {
				if (arg1 == null) {
					ret = LayoutInflater.from(getContext()).inflate(
							R.layout.item_list_teacher, null);
				} else {
					ret = arg1;
				}
				
				DMTeacher teacher = (DMTeacher) mData.get(arg0);
				UIHelper.setText(ret, R.id.teacher_name,
						teacher.getTeacherName());
				UIHelper.asyncLoadCircleImage(
						(ImageView) ret.findViewById(R.id.teacher_img),
						teacher.getIconUrl(),
						R.drawable.default_icon);
			}
			return ret;
		}
	}
	
	// innner ListView
	
    public OutScrollView parentScrollView;
    int currentY;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (parentScrollView == null) {
            return super.onInterceptTouchEvent(ev);
        } else {
        	// tab非置顶时inner scroll不获取scroll事件。
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
				if (parentScrollView.isTabTop()) {
					// 将父scrollview的滚动事件拦截
					currentY = (int) ev.getY();
					Utils.logd("CMM6, action_down tabTop and currentY = " + currentY);
					setParentScrollAble(false);
				}
                return super.onInterceptTouchEvent(ev);
            } else if (ev.getAction() == MotionEvent.ACTION_UP) {
                // 把滚动事件恢复给父Scrollview
                setParentScrollAble(true);
				Utils.logd("CMM6, action_up");
            } else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
            	
            }
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (parentScrollView != null) {
            if (ev.getAction() == MotionEvent.ACTION_MOVE) {
                int height = getContentHeight(this) - getHeight();
                int scrollY = getMyScrollY();
                int y = (int)ev.getY();
                
				// 手指向下滑动
                Utils.logd("CMM6 slide up or down scrollY = " + scrollY + ", y = " + y);
				if (currentY < y) {
					if (scrollY <= 0 || !parentScrollView.isTabTop()) {
						// 如果向下滑动到头 或者 非置顶，就把滚动交给父Scrollview
						setParentScrollAble(true);
					} else {
						setParentScrollAble(false);
					}
				} else if (currentY > y) {
					// 如果向上滑动到头 或者 非置顶，就把滚动交给父Scrollview
					if (scrollY >= height || !parentScrollView.isTabTop()) {
						setParentScrollAble(true);
					} else {
						setParentScrollAble(false);
					}

				}
				currentY = y;
            }
        }

        return super.onTouchEvent(ev);
    }

    /**
     * 是否把滚动事件交给父scrollview
     * 
     * @param flag
     */
    private void setParentScrollAble(boolean flag) {
    	Utils.logd("CMM6 requestParentScrollAble flag = " + flag);
        parentScrollView.requestDisallowInterceptTouchEvent(!flag);
    }
    /**
    * 动态设置ListView的高度
    * @param listView
    */
    public static int getContentHeight(ListView listView) { 
		if (listView == null)
			return 0;

        ListAdapter listAdapter = listView.getAdapter(); 
        if (listAdapter == null) { 
            // pre-condition 
            return 0; 
        }
        
        View listItem = listView.getChildAt(0);
        if (listItem == null) {
        	return 0;
        }

        int totalHeight = 0; 
        for (int i = 0; i < listAdapter.getCount(); i++) { 
            totalHeight += listItem.getHeight(); 
        } 

        ViewGroup.LayoutParams params = listView.getLayoutParams(); 
        int temp = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); 
        return temp;
    }

    /**
     * 计算每个item等高的listview
     * @return
     */
	public int getMyScrollY() {
		View c = getChildAt(0);
		if (c == null) {
			return 0;
		}
		int firstVisiblePosition = getFirstVisiblePosition();
		int top = c.getTop();
		return -top + firstVisiblePosition * c.getHeight();
	}
}


